/*
 * Copyright (c) 2006-2018, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2012-10-02     Yi Qiu       first version
 * 2012-12-12     heyuanjie87  change endpoints and function handler 
 * 2013-06-25     heyuanjie87  remove SOF mechinism
 * 2013-07-20     Yi Qiu       do more test
 * 2016-02-01     Urey         Fix some error
 * 2020-04-17     heyuanjie87  using File Operations
 */

#include <rthw.h>
#include <rtthread.h>
#include <rtservice.h>
#include <rtdevice.h>
#include <drivers/serial.h>
#include <drivers/usb/cdc.h>

#include <dfs_file.h>
#include <dfs_poll.h>

#define DBG_ENABLE
#define DBG_LEVEL    DBG_LOG
#define DBG_TAG      "UD-ACM"
#include <rtdbg.h>

#ifdef RT_USB_DEVICE_CDC

#define CDC_RX_BUFSIZE          128
#define CDC_MAX_PACKET_SIZE     64
#define VCOM_DEVICE             "vcom"

#ifdef RT_VCOM_SERNO
#define _SER_NO RT_VCOM_SERNO
#else /*!RT_VCOM_SERNO*/
#define _SER_NO  "32021919830108"
#endif /*RT_VCOM_SERNO*/

#ifdef RT_VCOM_SER_LEN
#define _SER_NO_LEN RT_VCOM_SER_LEN
#else /*!RT_VCOM_SER_LEN*/
#define _SER_NO_LEN 14 /*rt_strlen("32021919830108")*/
#endif /*RT_VCOM_SER_LEN*/

#define CDC_TX_BUFSIZE    1024
#define CDC_BULKIN_MAXSIZE (CDC_TX_BUFSIZE / 8)

#define CDC_TX_HAS_DATE   0x01

ALIGN(4)
static struct udevice_descriptor dev_desc =
{
    USB_DESC_LENGTH_DEVICE,     //bLength;
    USB_DESC_TYPE_DEVICE,       //type;
    USB_BCD_VERSION,            //bcdUSB;
    USB_CLASS_CDC,              //bDeviceClass;
    0x00,                       //bDeviceSubClass;
    0x00,                       //bDeviceProtocol;
    CDC_MAX_PACKET_SIZE,          //bMaxPacketSize0;
    _VENDOR_ID,                 //idVendor;
    _PRODUCT_ID,                //idProduct;
    USB_BCD_DEVICE,             //bcdDevice;
    USB_STRING_MANU_INDEX,      //iManufacturer;
    USB_STRING_PRODUCT_INDEX,   //iProduct;
    USB_STRING_SERIAL_INDEX,    //iSerialNumber;
    USB_DYNAMIC,                //bNumConfigurations;
};

//FS and HS needed
ALIGN(4)
static struct usb_qualifier_descriptor dev_qualifier =
{
    sizeof(dev_qualifier),          //bLength
    USB_DESC_TYPE_DEVICEQUALIFIER,  //bDescriptorType
    0x0200,                         //bcdUSB
    USB_CLASS_CDC,                  //bDeviceClass
    0x00,                           //bDeviceSubClass
    0x00,                           //bDeviceProtocol
    64,                             //bMaxPacketSize0
    0x01,                           //bNumConfigurations
    0,
};

/* communcation interface descriptor */
ALIGN(4)
const static struct ucdc_comm_descriptor _comm_desc =
{
#ifdef RT_USB_DEVICE_COMPOSITE
    /* Interface Association Descriptor */
    {
        USB_DESC_LENGTH_IAD,
        USB_DESC_TYPE_IAD,
        USB_DYNAMIC,
        0x02,
        USB_CDC_CLASS_COMM,
        USB_CDC_SUBCLASS_ACM,
        USB_CDC_PROTOCOL_V25TER,
        0x00,
    },
#endif
    /* Interface Descriptor */
    {
        USB_DESC_LENGTH_INTERFACE,
        USB_DESC_TYPE_INTERFACE,
        USB_DYNAMIC,
        0x00,   
        0x01,
        USB_CDC_CLASS_COMM,
        USB_CDC_SUBCLASS_ACM,
        USB_CDC_PROTOCOL_V25TER,
        0x00,
    },
    /* Header Functional Descriptor */   
    {
        0x05,                              
        USB_CDC_CS_INTERFACE,
        USB_CDC_SCS_HEADER,
        0x0110,
    },
    /* Call Management Functional Descriptor */   
    {
        0x05,            
        USB_CDC_CS_INTERFACE,
        USB_CDC_SCS_CALL_MGMT,
        0x00,
        USB_DYNAMIC,
    },
    /* Abstract Control Management Functional Descriptor */
    {
        0x04,
        USB_CDC_CS_INTERFACE,
        USB_CDC_SCS_ACM,
        0x02,
    },
    /* Union Functional Descriptor */   
    {
        0x05,
        USB_CDC_CS_INTERFACE,
        USB_CDC_SCS_UNION,
        USB_DYNAMIC,
        USB_DYNAMIC,
    },
    /* Endpoint Descriptor */    
    {
        USB_DESC_LENGTH_ENDPOINT,
        USB_DESC_TYPE_ENDPOINT,
        USB_DYNAMIC | USB_DIR_IN,
        USB_EP_ATTR_INT,
        0x08,
        0xFF,
    },
};

/* data interface descriptor */
ALIGN(4)
const static struct ucdc_data_descriptor _data_desc =
{
    /* interface descriptor */
    {
        USB_DESC_LENGTH_INTERFACE,
        USB_DESC_TYPE_INTERFACE,
        USB_DYNAMIC,
        0x00,
        0x02,         
        USB_CDC_CLASS_DATA,
        0x00,                             
        0x00,                             
        0x00,              
    },
    /* endpoint, bulk out */
    {
        USB_DESC_LENGTH_ENDPOINT,     
        USB_DESC_TYPE_ENDPOINT,
        USB_DYNAMIC | USB_DIR_OUT,
        USB_EP_ATTR_BULK,      
        USB_CDC_BUFSIZE,
        0x00,          
    },
    /* endpoint, bulk in */
    {
        USB_DESC_LENGTH_ENDPOINT,
        USB_DESC_TYPE_ENDPOINT,
        USB_DYNAMIC | USB_DIR_IN,
        USB_EP_ATTR_BULK,      
        USB_CDC_BUFSIZE,
        0x00,
    },
};
ALIGN(4)
static char serno[_SER_NO_LEN + 1] = {'\0'};
RT_WEAK rt_err_t vcom_get_stored_serno(char *serno, int size);

rt_err_t vcom_get_stored_serno(char *serno, int size)
{
    return RT_ERROR;
}
ALIGN(4)
const static char* _ustring[] =
{
    "Language",
    "RT-Thread Team.",
    "RTT Virtual Serial",
    serno,
    "Configuration",
    "Interface",
};

struct acm_device
{
    struct rt_device parent;
    uep_t ep_out;
    uep_t ep_in;
    uep_t ep_cmd;

    struct rt_wqueue wq;
    struct rt_wqueue rq;
    rt_list_t wcomp;
    rt_list_t rcomp;
    int connected;
    struct ucdc_line_coding line_coding;
};

static void _vcom_reset_state(ufunction_t func)
{

}

/**
 * This function will handle cdc bulk in endpoint request.
 *
 * @param func the usb function object.
 * @param size request size.
 *
 * @return RT_EOK.
 */
static void _ep_in_handler(uep_t ep, uio_request_t req)
{
    ufunction_t func = (ufunction_t)req->user_data;
    struct acm_device * wd = (struct acm_device *)func->user_data;

    if (req->actual <= 0)
    {

    }
    else
    {
        rt_list_insert_after(&wd->wcomp, &req->list);
        rt_wqueue_wakeup(&(wd->wq), (void *)POLLOUT);
    }
}

/**
 * This function will handle cdc bulk out endpoint request.
 *
 * @param func the usb function object.
 * @param size request size.
 *
 * @return RT_EOK.
 */
static void _ep_out_handler(uep_t ep, uio_request_t req)
{
    ufunction_t func = (ufunction_t)req->user_data;
    struct acm_device * wd = (struct acm_device *)func->user_data;

    if (req->actual <= 0)
    {
        rt_usbd_io_request(func->device, wd->ep_out, req);
    }
    else
    {
        rt_list_insert_after(&wd->rcomp, &req->list);
        rt_wqueue_wakeup(&(wd->rq), (void *)POLLIN);
    }
}

/**
 * This function will handle cdc interrupt in endpoint request.
 *
 * @param device the usb device object.
 * @param size request size.
 *
 * @return RT_EOK.
 */
static rt_err_t _ep_cmd_handler(ufunction_t func, uio_request_t req)
{

    return 0;
}

static void _cdc_set_line_coding_callback(uep_t ep, uio_request_t req)
{
    ufunction_t func = (ufunction_t)req->user_data;
    struct acm_device *wd = (struct acm_device *)func->user_data;

    LOG_D("set_line_coding complete\n");
    rt_memcpy(&wd->line_coding, req->buffer, sizeof(wd->line_coding));

    dcd_ep0_send_status(func->device->dcd);
}

/**
 * This function will handle cdc_get_line_coding request.
 *
 * @param device the usb device object.
 * @param setup the setup request.
 *
 * @return RT_EOK on successful.
 */
static int _cdc_get_line_coding(ufunction_t func, ureq_t setup)
{
    uint16_t size;
    struct acm_device *wd = (struct acm_device *)func->user_data;

    LOG_D("get_line_coding\n");

    size = setup->wLength > 7 ? 7 : setup->wLength;

    rt_usbd_ep0_write(func->device, (void*)&wd->line_coding, size, RT_NULL, RT_NULL);

    return RT_EOK;
}

/**
 * This function will handle cdc_set_line_coding request.
 *
 * @param device the usb device object.
 * @param setup the setup request.
 *
 * @return RT_EOK on successful.
 */
static int _cdc_set_line_coding(ufunction_t func, ureq_t setup)
{
    RT_ASSERT(setup != RT_NULL);

    LOG_D("set_line_coding\n");

    rt_usbd_ep0_read(func->device, sizeof(struct ucdc_line_coding),
        _cdc_set_line_coding_callback, func);

    return RT_EOK;
}

/**
 * This function will handle cdc interface request.
 *
 * @param device the usb device object.
 * @param setup the setup request.
 *
 * @return RT_EOK on successful.
 */
static rt_err_t _interface_handler(ufunction_t func, ureq_t setup)
{
    struct acm_device *data;

    RT_ASSERT(func != RT_NULL);
    RT_ASSERT(func->device != RT_NULL);
    RT_ASSERT(setup != RT_NULL);

    data = (struct acm_device*)func->user_data;
    
    switch(setup->bRequest)
    {
    case CDC_SEND_ENCAPSULATED_COMMAND:
        break;
    case CDC_GET_ENCAPSULATED_RESPONSE:
        break;
    case CDC_SET_COMM_FEATURE:
        break;
    case CDC_GET_COMM_FEATURE:
        break;
    case CDC_CLEAR_COMM_FEATURE:
        break;
    case CDC_SET_LINE_CODING:
        _cdc_set_line_coding(func, setup);
        break;
    case CDC_GET_LINE_CODING:
        _cdc_get_line_coding(func, setup);
        break;
    case CDC_SET_CONTROL_LINE_STATE:
        data->connected = setup->wValue;
        dcd_ep0_send_status(func->device->dcd);

        LOG_D("vcom state:%d\n", data->connected);
        break;
    case CDC_SEND_BREAK:
        break;
    default:
        LOG_W("unknown cdc request %X\n",setup->request_type);
        return -1;
    }

    return 0;
}

/**
 * This function will run cdc function, it will be called on handle set configuration request.
 *
 * @param func the usb function object.
 *
 * @return RT_EOK on successful.
 */
static rt_err_t _function_enable(ufunction_t func)
{
    struct acm_device *wd;
    struct uio_request *req;

    RT_ASSERT(func != RT_NULL);
    wd = func->user_data;


    req = rt_usbd_req_alloc(EP_MAXPACKET(wd->ep_in), _ep_in_handler, func);
    rt_list_insert_after(&wd->wcomp, &req->list);
    req = rt_usbd_req_alloc(EP_MAXPACKET(wd->ep_out), _ep_out_handler, func);
    rt_usbd_io_request(func->device, wd->ep_out, req);

    return 0;
}

/**
 * This function will stop cdc function, it will be called on handle set configuration request.
 *
 * @param func the usb function object.
 *
 * @return RT_EOK on successful.
 */
static rt_err_t _function_disable(ufunction_t func)
{
    struct acm_device *wd;

    RT_ASSERT(func != RT_NULL);
    wd = func->user_data;

    rt_wqueue_wakeup(&(wd->rq), (void *)POLLHUP);
    rt_wqueue_wakeup(&(wd->wq), (void *)POLLHUP);

    return 0;
}

static struct ufunction_ops ops =
{
    _function_enable,
    _function_disable,
    RT_NULL,
};

/**
 * This function will configure cdc descriptor.
 *
 * @param comm the communication interface number.
 * @param data the data interface number.
 *
 * @return RT_EOK on successful.
 */
static rt_err_t _cdc_descriptor_config(ucdc_comm_desc_t comm, 
    rt_uint8_t cintf_nr, ucdc_data_desc_t data, rt_uint8_t dintf_nr)
{
    comm->call_mgmt_desc.data_interface = dintf_nr;
    comm->union_desc.master_interface = cintf_nr;
    comm->union_desc.slave_interface0 = dintf_nr;
#ifdef RT_USB_DEVICE_COMPOSITE
    comm->iad_desc.bFirstInterface = cintf_nr;
#endif

    return 0;
}

/**
 * This function will create a cdc function instance.
 *
 * @param device the usb device object.
 *
 * @return RT_EOK on successful.
 */
ufunction_t rt_usbd_function_cdc_create(udevice_t device)
{
    ufunction_t func;
    struct acm_device* data;
    uintf_t intf_comm, intf_data;
    ualtsetting_t comm_setting, data_setting;
    ucdc_data_desc_t data_desc;
    ucdc_comm_desc_t comm_desc;

    /* parameter check */
    RT_ASSERT(device != RT_NULL);

    rt_memset(serno, 0, _SER_NO_LEN + 1);
    if(vcom_get_stored_serno(serno, _SER_NO_LEN) != RT_EOK)
    {
        rt_memset(serno, 0, _SER_NO_LEN + 1);
        rt_memcpy(serno, _SER_NO, rt_strlen(_SER_NO));
    }
    /* set usb device string description */
    rt_usbd_device_set_string(device, _ustring);
    
    /* create a cdc function */
    func = rt_usbd_function_new(device, &dev_desc, &ops);
    //not support HS
    //rt_usbd_device_set_qualifier(device, &dev_qualifier);

    /* allocate memory for cdc vcom data */
    data = (struct acm_device*)rt_calloc(1, sizeof(struct acm_device));
    func->user_data = (void*)data;

    /* initilize vcom */
    rt_usb_vcom_init(func);

    /* create a cdc communication interface and a cdc data interface */
    intf_comm = rt_usbd_interface_new(device, _interface_handler);
    intf_data = rt_usbd_interface_new(device, _interface_handler);

    /* create a communication alternate setting and a data alternate setting */
    comm_setting = rt_usbd_altsetting_new(sizeof(struct ucdc_comm_descriptor));
    data_setting = rt_usbd_altsetting_new(sizeof(struct ucdc_data_descriptor));

    /* config desc in alternate setting */
    rt_usbd_altsetting_config_descriptor(comm_setting, &_comm_desc,
                                         (rt_off_t)&((ucdc_comm_desc_t)0)->intf_desc);
    rt_usbd_altsetting_config_descriptor(data_setting, &_data_desc, 0);
    /* configure the cdc interface descriptor */
    _cdc_descriptor_config(comm_setting->desc, intf_comm->intf_num, data_setting->desc, intf_data->intf_num);

    /* create a command endpoint */
    comm_desc = (ucdc_comm_desc_t)comm_setting->desc;
    data->ep_cmd = rt_usbd_endpoint_new(&comm_desc->ep_desc);

    /* add the command endpoint to the cdc communication interface */
    rt_usbd_altsetting_add_endpoint(comm_setting, data->ep_cmd);

    /* add the communication alternate setting to the communication interface,
       then set default setting of the interface */
    rt_usbd_interface_add_altsetting(intf_comm, comm_setting);
    rt_usbd_set_altsetting(intf_comm, 0);

    /* add the communication interface to the cdc function */
    rt_usbd_function_add_interface(func, intf_comm);

    /* create a bulk in and a bulk endpoint */
    data_desc = (ucdc_data_desc_t)data_setting->desc;
    data->ep_out = rt_usbd_endpoint_new(&data_desc->ep_out_desc);
    data->ep_in = rt_usbd_endpoint_new(&data_desc->ep_in_desc);

    /* add the bulk out and bulk in endpoints to the data alternate setting */
    rt_usbd_altsetting_add_endpoint(data_setting, data->ep_in);
    rt_usbd_altsetting_add_endpoint(data_setting, data->ep_out);

    /* add the data alternate setting to the data interface
            then set default setting of the interface */
    rt_usbd_interface_add_altsetting(intf_data, data_setting);
    rt_usbd_set_altsetting(intf_data, 0);

    /* add the cdc data interface to cdc function */
    rt_usbd_function_add_interface(func, intf_data);
    
    return func;
}

/* file operations */
static int _file_open(struct dfs_fd *fd)
{
    return 0;
}

static int _file_close(struct dfs_fd *fd)
{
    return 0;
}

static int _file_ioctl(struct dfs_fd *fd, int cmd, void *args)
{
    return 0;
}

static int _file_read(struct dfs_fd *fd, void *buf, size_t size)
{
    struct acm_device *wd;
    struct ufunction *f;
    size_t rsize, tsize;
    struct uio_request *req;

    wd = (struct acm_device *)fd->data;
    f = (struct ufunction *)wd->parent.user_data;

    if (!f->enabled)
        return -ENODEV;

    while (rt_list_isempty(&wd->rcomp))
    {
        if (fd->flags & O_NONBLOCK)
            return -EAGAIN;

        rt_wqueue_wait(&wd->rq, 0, RT_WAITING_FOREVER);
        if (!f->enabled)
            return -ENODEV;
    }

    req = rt_list_first_entry(&wd->rcomp, struct uio_request, list);
    rsize = size > req->actual? req->actual : size;
    rt_memcpy(buf, req->buffer + req->pos, rsize);
    req->actual -= rsize;
    req->pos += rsize;
    if (req->actual == 0)
    {
        rt_list_remove(&req->list);
        rt_usbd_io_request(f->device, wd->ep_out, req);
    }

    return rsize;
}

static int _file_write(struct dfs_fd *fd, const void *buf, size_t size)
{
    struct acm_device *wd;
    struct ufunction *f;
    struct uio_request *req;
    int wlen;

    wd = (struct acm_device *)fd->data;
    f = (struct ufunction *)wd->parent.user_data;

    if (!f->enabled)
        return -ENODEV;

    while (rt_list_isempty(&wd->wcomp))
    {
        if (fd->flags & O_NONBLOCK)
            return -EAGAIN;

        rt_wqueue_wait(&wd->wq, 0, RT_WAITING_FOREVER);
        if (!f->enabled)
            return -ENODEV;
    }

    req = rt_list_first_entry(&wd->wcomp, struct uio_request, list);;
    rt_list_remove(&req->list);
    wlen = size > req->bufsz? req->bufsz : size;
    req->size = wlen;
    rt_memcpy(req->buffer, buf, wlen);

    rt_usbd_io_request(f->device, wd->ep_in, req);

    return wlen;
}

static int _file_poll(struct dfs_fd *fd, struct rt_pollreq *req)
{
    int mask = 0;
    struct acm_device *wd;
    struct ufunction *f;

    wd = (struct acm_device *)fd->data;
    f = (struct ufunction *)wd->parent.user_data;

    if (!f->enabled)
        return POLLHUP;
    if (!rt_list_isempty(&wd->rcomp))
        mask |= POLLIN;
    else
        rt_poll_add(&wd->rq, req);

    if (!rt_list_isempty(&wd->wcomp))
        mask |= POLLOUT;
    else
        rt_poll_add(&wd->wq, req);

    return mask;
}

static const struct dfs_file_ops _fops =
{
    _file_open,
    _file_close,
    _file_ioctl,
    _file_read,
    _file_write,
    RT_NULL,
    RT_NULL,
    RT_NULL,
    _file_poll
};

static int rt_usb_vcom_init(struct ufunction *func)
{
    int ret;
    struct acm_device *wd = (struct acm_device*)func->user_data;

    wd->line_coding.dwDTERate = 115200;
    wd->line_coding.bCharFormat = 0;
    wd->line_coding.bDataBits = 8;
    wd->line_coding.bParityType = 0;

    wd->parent.user_data = func;
    /* register vcom device */
    ret = rt_device_register(&wd->parent, VCOM_DEVICE, 0);
    wd->parent.fops = &_fops;
    rt_wqueue_init(&wd->rq);
    rt_wqueue_init(&wd->wq);
    rt_list_init(&wd->rcomp);
    rt_list_init(&wd->wcomp);

    return ret;
}

struct udclass vcom_class = 
{
    .rt_usbd_function_create = rt_usbd_function_cdc_create
};

int rt_usbd_vcom_class_register(void)
{
    rt_usbd_class_register(&vcom_class);
    return 0;
}
INIT_PREV_EXPORT(rt_usbd_vcom_class_register);

#endif
